<template>
  <q-page>
    <q-inner-loading visible v-if="model.id==0">
      <q-spinner-gears size="50px" color="primary"></q-spinner-gears>
      <b class="text-primary">数据加载中...</b>
    </q-inner-loading>

    <div class="bg-primary row q-toolbar text-center text-white">
      <div class="col-12"><small>{{model.releaseDate}}上映</small>
        <q-btn class="float-right" flat round dense icon="mdi-settings" @click="toggleSetting(false)" />
      </div>
      <div class="col-4">
        <div><label class="q-display-1">{{score>0?(score/10).toFixed(3):'未开'}}</label> 分</div>
        <div><small>{{model.ratingCount}}人评分</small></div>
      </div>
      <div class="col-8 text-left q-pa-sm">
        <div>距离 <b>{{(targetScore(1)/10).toFixed(1)}}</b> 分还差</div>
        <div><small> {{scoreDetail(1)}}</small> </div>
      </div>
    </div>
    
    <div class="row">
      <!-- score rate -->
      <q-card class="col-xs-12 col-md-6">
        <q-card-title>评分分布 
          <small slot="right" v-if="predicts.length>0">（预测样本：{{predicts[predicts.length-1].ratingCount}}）</small>
          </q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="chart1Options" auto-resize ref="chart1" />
        </q-card-main>
      </q-card>
      <!-- score rate -->
      <q-card class="col-xs-12 col-md-6">
        <q-card-title>评分走势
          <q-btn-toggle slot="right" dense v-model="scoreType" toggle-color="primary"
            :options="[
              {label: '近期走势', value: 'day'},
              {label: '今日走势', value: 'hour'}
            ]"
          />
        </q-card-title>
        <q-card-separator />
        <q-card-main>
          <v-chart :options="chart2Options" auto-resize ref="chart2" />
        </q-card-main>
      </q-card>
    </div>  

    <!-- modal -->
    <q-modal v-if="model.id>0" v-model="setting.modal" :position="$q.platform.is.mobile?'':'right'" :maximized="$q.platform.is.mobile">      
      <q-toolbar color="primary">
        <q-toolbar-title>影片设置</q-toolbar-title>
        <q-btn flat round dense icon="mdi-close" @click="toggleSetting(false)" />
      </q-toolbar>
      <q-list separator no-border>
        <q-list-header>
            影片设置 <label class="float-right text-primary" v-if="model.name">《{{ model.name }}》</label>
        </q-list-header>
        <q-item>
            <q-item-side icon="star" color="red" />
            <q-item-main>
                <q-item-tile label>特别关注</q-item-tile>
                <q-item-tile sublabel>特别关注的影片将出现在影片列表页的[置顶]位置中。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedTop" color="red" @input="onToggleTop" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="email" color="primary" />
            <q-item-main>
                <q-item-tile label>开分提醒</q-item-tile>
                <q-item-tile sublabel>影片开分或评分发生变化时会进行邮件提醒。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedMonitor"  @input="onToggleMonitor" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="bar_chart" color="primary" />
            <q-item-main>
                <q-item-tile label>数据跟踪</q-item-tile>
                <q-item-tile sublabel>跟踪影片的评分、想看人数、看过人数等数据的每日变化情况。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.checkedScore"  @input="onToggleScore"/>
            </q-item-side>
        </q-item>

        <q-list-header>默认功能 <small>(影评上映期间自动进行)</small></q-list-header>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>评分预测</q-item-tile>
                <q-item-tile sublabel>影片开分前对影片的得分进行预估。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>用户评论</q-item-tile>
                <q-item-tile sublabel>定期获取影片的用户评论数据。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>长评短评</q-item-tile>
                <q-item-tile sublabel>定期获取影片的用户短评及影评数据。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
        <q-item>
            <q-item-side icon="done" color="secondary" />
            <q-item-main>
                <q-item-tile label>口碑分析</q-item-tile>
                <q-item-tile sublabel>根据用户长短评进行关键词提取。</q-item-tile>
            </q-item-main>
            <q-item-side right>
                <q-toggle v-model="setting.dftToggle" disable color="secondary" />
            </q-item-side>
        </q-item>
      </q-list>
    </q-modal>
  </q-page>
</template>

<script>
let _tootipRateFormatter = function(param) {
  let str = param.length>0?param[0].name:'';
  for(let i = 0; i < param.length; i++) {
      str = str + '<br/>' 
          + param[i].seriesName + '：' 
          + (param[i].value/10).toFixed(1) + '%';
  }
  return str;
};

// chart1 : score rate bar chart
let _chart1Options = {
    tooltip : {
        trigger: 'axis',
        axisPointer : {
            type : 'shadow' 
        },
        formatter: _tootipRateFormatter
    },
    legend: {
        data:['豆瓣分布', '预测分布']
    },
    grid: {
        left: 0,
        right: '25px',
        top: '25px',
        bottom: 0,
        containLabel: true
    },
    xAxis : [
        {
            show : false
        }
    ],
    yAxis : [
        {
            data : ['五星','四星','三星','两星','一星'],
            inverse : true
        }
    ],
    series : [
        {
            name:'豆瓣分布',
            type:'bar',
            label: {
                show: true,
                position: 'right',
                formatter: function(param){
                    return (param.value/10).toFixed(1) + '%';
                }
            },
            data:[0, 0, 0, 0, 0]
        },
        {
            name:'预测分布',
            type:'bar',
            label: {
                show: true,
                position: 'right',
                formatter: function(param){
                    return (param.value/10).toFixed(1) + '%';
                }
            },
            data:[0, 0, 0, 0, 0]
        }
    ]
};
// chart2 : day score line chart
let _chart2Options = {
    tooltip: {
        trigger: 'axis',
        formatter: _tootipRateFormatter
    },
    legend: {
        data:['五星占比','四星占比','三星占比','两星占比','一星占比']
    },
    grid: {
        left: 0,
        right: '5px',
        top: '25px',
        bottom: 0,
        containLabel: true
    },
    xAxis: {
        type: 'category',
        data: []
    },
    yAxis: {
        type: 'value',
        axisLabel: {
            formatter: function (value) {
                return (value/10).toFixed(1) + '%';
            }
        }
    },
    series: [
        {
            name:'五星占比',
            type:'line',
            data:[]
        },
        {
            name:'四星占比',
            type:'line',
            data:[]
        },
        {
            name:'三星占比',
            type:'line',
            data:[]
        },
        {
            name:'两星占比',
            type:'line',
            data:[]
        },
        {
            name:'一星占比',
            type:'line',
            data:[]
        }
    ]
};

export default {
  name: 'PageMovieScore',
  data() {
    let data = []

    for (let i = 0; i <= 360; i++) {
        let t = i / 180 * Math.PI
        let r = Math.sin(2 * t) * Math.cos(2 * t)
        data.push([r, i])
    }

    return {
      model: {
        id:0,
        name:'',
        releaseDate:'',
        year:0,
        marks:'',
        score:0,
        ratingCount:0,
        commentCount:0,
        wishCount:0,
        star5Rate:133,
        star4Rate:458,
        star3Rate:365,
        star2Rate:40,
        star1Rate:4
      },
      setting:{
        modal: false,
        dftToggle: true,
        checkedTop: false,
        checkedMonitor: false,
        checkedScore: false
      },
      scoreType: 'day',
      scores: [],
      scoreRates:[0,0,0,0,0],
      predicts: [],
      predictRates:[0,0,0,0,0],
      chart1Options: _chart1Options, 
      chart2Options: _chart2Options  
    }
  },
  mounted() {
    let me = this;
    this.$api.ui.pageTitle = '豆瓣影片';
    this.loadMovie();
    this.loadScores();
    this.loadPredicts();
    if(this.$route.query.setting=='true') {
      this.toggleSetting(true);
    }
  },
  methods: {
    toggleSetting(open) {
      this.setting.modal = open;
    },
    loadMovie() {
      let me = this;
      let id = this.$route.params.id;
      this.$api.movie.loadOneMovie(id, res => {
        let data = res.data.model;
        me.$api.ui.pageTitle = data.name;
        me.model = data;
        me.setting.checkedTop = (data.marks.indexOf('TOP') >= 0);
        me.setting.checkedMonitor = (data.marks.indexOf('MONITOR') >= 0);
        me.setting.checkedScore = (data.marks.indexOf('SCORE') >= 0);
      });
    },
    loadScores(isHour) {
      let me = this;
      let id = this.$route.params.id;
      if(isHour) {

      } else {
        this.$api.movie.loadScoresByDate(id, res => {
          let list = res.data.model;
          me.scores = list;
          if(list.length > 0) {
            me.scoreRates = list[list.length - 1].starRates;
            me.chart1Options.series[0].data = me.scoreRates;
          
            // 绑定折线图
            let startIndex = list.length > 14 ? list.length - 14 : 0;
            for(let i = startIndex; i < list.length; i++) {
              let item = list[i];
              _chart2Options.xAxis.data.push(item.showDate);
              for(let j = 0; j < 5; j++) {
                _chart2Options.series[j].data.push(item.starRates[j]);  
              }
            }
          }
        });
      }
    },

    loadPredicts() {
      let me = this;
      let id = this.$route.params.id;
      this.$api.movie.loadPredicts(id, res => {
        let list = res.data.model;
        me.predicts = list;
        if(list.length > 0) {
          me.predictRates = list[list.length - 1].starRates;
          me.chart1Options.series[1].data = me.predictRates;
        }
      });
    },

    onToggleChange(val, type) {
      this.$api.movie.doMarks(this.$route.params.id, type, val);
    },
    onToggleTop(val) {
      return this.onToggleChange(val, 'TOP');
    },
    onToggleMonitor(val) {
      return this.onToggleChange(val, 'MONITOR');
    },
    onToggleScore(val) {
      return this.onToggleChange(val, 'SCORE');
    },

    targetScore(delta) {
      return Math.round(this.exactScore) + delta - 0.49;
    },

    scoreDetail(delta) {
      let curScore = this.exactScore;
      let tarScore = Math.round(curScore) + delta - 0.49;
      let detail = '';
      let star5Num = this.scoreNum(tarScore, curScore, this.model.ratingCount, 100);      
      if(star5Num > 0) {
        detail += '五星 ('+star5Num+')';
      }
      let star4Num = this.scoreNum(tarScore, curScore, this.model.ratingCount, 80);
      if(star4Num > 0) {
        detail += '    四星 ('+star4Num+')';
      }
      console.log(detail + ';');
      return detail;
    },

    scoreNum(tarScore, curScore, rCount, starScore) {
      if(starScore - tarScore < 1 || rCount <= 0) {
        return 0;
      }
      return Math.round((tarScore - curScore) * rCount / (starScore - tarScore));
    }
  }, 
  computed: {
    exactScore() {
      let num = 0;
      for(let i = 0; i < 5; i++) {
        num += (10-2*i) * this.scoreRates[i];
      }
      return (num / 100);
    },
    score() {
      return this.exactScore > 0 ? this.exactScore : this.model.score;
    }
  }
}
</script>

<style>
.echarts {
  width: 100%;
  height: 300px;
}
</style>